import winston, { format } from 'winston';
import { inspect } from 'util';
import flogger, { support } from 'fluent-logger';

let floggerisAvailable = false;
let initFlogger = function() {
	let config = {
		host: 'localhost',
		port: 24224,
		timeout: 3,
	};
	flogger.configure('mj3d', config);
	flogger.on('error', error => {
		floggerisAvailable = false;
		console.log('fluentd error');
	});
	flogger.on('connect', () => {
		floggerisAvailable = true;
		console.log('fluentd connect');
	});
	// 必须发送一下才会连接
	flogger.emit('logger', { message: 'start' });
};

const filterDevice = format.combine(
	format(info => (info.device ? undefined : info))(),
	format.printf(info => {
		const time = new Date().toLocaleString();
		return `${time} [${info.label}] ${info.level}: ${info.message}`;
	}),
);
export const logger = winston.createLogger({
	level: 'info',
	transports: [
		new winston.transports.Console({ format: filterDevice }),
		new winston.transports.File({
			format: filterDevice,
			filename: 'logs/error.log',
			level: 'error',
		}),
		new winston.transports.File({
			format: filterDevice,
			filename: 'logs/combined.log',
		}),
		new winston.transports.File({
			filename: 'logs/device.log',
			format: format.combine(
				format(info => (!info.device ? undefined : info))(),
				format.printf(info => {
					return `${info.device}: ${info.message}`;
				}),
			),
		}),
	],
});

export const makeLabelLogger = function(label) {
	const convertArgs = args => {
		let cargs = args.map(v => {
			if (typeof v == 'string') return v;
			if (typeof v == 'number') return v;
			return inspect(v);
		});
		return cargs;
	};
	const llog = (...args) => {
		let cargs = convertArgs(args);
		let str = cargs.join(', ');
		logger.info(str, { label });
		if (floggerisAvailable) flogger.emit(label, { label, message: str });
	};
	const lerror = (...args) => {
		let cargs = convertArgs(args);
		let str = cargs.join(', ');
		logger.error(str, { label });
		if (floggerisAvailable) flogger.emit(label, { label, message: str });
	};
	return { llog, lerror };
};

export const { llog, lerror } = makeLabelLogger('mb');
llog('************************');
llog(`*** start pid: ${process.pid} ***`);
llog('************************');
// process.exit(1);
